package cloud.lysky.java.on.concurrent.exchanger;

import java.util.concurrent.Exchanger;

/**
 * @author luoly
 * @describe
 * @date 2023/3/20 14:07
 **/
// 模拟交易案例
public class ExchangerDemo {
    private static final Exchanger<String> exchanger = new Exchanger<>();
    static String goods = "电脑";
    static String money = "￥6299";
    public static void main(String[] args) throws InterruptedException {
        System.out.println("准备交易，一手交钱一手交货...");
        //卖家
        new Thread(() -> {
            System.out.println("卖家到了，已经准备好货: " + goods);
            try{
                String money = exchanger.exchange(goods);
                System.out.println("卖家已收到钱: " + money);
            } catch (Exception e) {
              e.printStackTrace();
            }
        }).start();
        Thread.sleep(3000);
        //买家
        new Thread(() -> {
            try {
                System.out.println("买家到了，已准备好钱: " + money);
                String goods = exchanger.exchange(money);
                System.out.println("买家已收到货:" + goods);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
}
